package com.qf.p1.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.p1.model.Course;
import com.qf.p1.model.CourseTname;
import com.qf.p1.model.User;
import com.qf.p1.result.R;
import com.qf.p1.service.CourseService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 课程的Controller
 * @version v1.0.0
 * @Description:
 * @author: 姜红凯
 * @date: 2022.04.06
 * @since 1.0
 */
@RestController
@RequestMapping("Demo/course")
public class CourseController {

    @Resource
    private CourseService courseService;

    @PostMapping("page")
    public R page(@RequestBody JSONObject pageDTO){
        Integer pageNo=pageDTO.getInteger("pageNo");
        Integer pageSize=pageDTO.getInteger("pageSize");
        String likeName=pageDTO.getString("likeName");
        List<CourseTname> courses = courseService.pageData(pageNo, pageSize,likeName);
        int pageCount = courseService.pageCount(pageSize,likeName);
        return R.ok()
                .setResult("courses",courses)
                .setResult("pageCount",pageCount);
    }

    @DeleteMapping("course")
    public R delete(@RequestBody JSONObject delDTO){
        Integer cid = delDTO.getInteger("cid");
        int result = courseService.deleteCourse(cid);
        if (result==0){
            return R.ok("删除课程失败");
        }
        return R.ok("删除课程成功");
    }

    @PostMapping("course")
    public R add(@RequestBody JSONObject addDTO){
        String name = addDTO.getString("name");
        String teacherName = addDTO.getString("teacherName");
        Integer sMax = addDTO.getInteger("sMax");
        int result=courseService.addCourse(name,teacherName,sMax);

        if (result==0){
            return R.ok("新增课程失败");
        }
        return R.ok("新增课程成功");
    }
    @PutMapping("course")
    public R edit(@RequestBody JSONObject editObject){
        Integer cid = editObject.getInteger("cid");
        String name = editObject.getString("name");
        String teacherName = editObject.getString("teacherName");
        Integer sMax = editObject.getInteger("sMax");

        int result=courseService.updateCourse(cid,name,teacherName);
        if(result==0){
            return R.ok("修改失败");
        }else {
            return R.ok("修改成功");
        }
    }
    @PostMapping("users")
    public R findUsers(@RequestBody JSONObject jsonObject){
        Integer cid = jsonObject.getInteger("cid");
        List<User> users = courseService.findUserByCid(cid);
        return R.ok("查询成功").setResult("users",users);
    }
}
